'use strict';

const { Service } = require('egg');
const https = require('https');

class FlyService extends Service {
  getWeather(city, date) {
    return new Promise((resolve, reject) => {
      https.request('https://www.tianqiapi.com/api?version=v9&appid=22152472&appsecret=2rNTJAvg&city='
        + encodeURIComponent(city), res => {
        if (res.statusCode === 200) {
          let data = '';
          res.on('data', chunk => { data += chunk; });
          res.on('end', () => {
            const dt = JSON.parse(data);
            for (const item of dt.data) {
              const date2 = new Date(item.date);
              if (date.getFullYear() === date2.getFullYear() && date.getMonth() === date2.getMonth() && date.getDate() === date2.getDate()) {
                resolve(item.wea_day + '，温度' + item.tem2 + '~' + item.tem1 + '℃。' + item.air_tips);
                return;
              }
            }
            reject(new Error('日期太久远啦'));
          });
        } else {
          reject(new Error('服务器错误'));
        }
      }).on('error', e => {
        console.error(e);
      }).end();
    });
  }
}

module.exports = FlyService;
